/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.entity.dto.AppLoginDTO;
import io.renren.modules.app.entity.dto.AppRegisterDTO;
import io.renren.modules.app.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByPhone(String phone) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
	}

	@Override
	public long login(AppLoginDTO form) {
		UserEntity user = queryByPhone(form.getPhone());
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(new Sha256Hash(form.getPassword(),user.getSalt()).toHex())){
			throw new RRException("手机号或密码错误");
		}

		return user.getId();
	}

	@Override
	public UserEntity queryByUserPhone(String phone) {
		return this.getOne(new QueryWrapper<UserEntity>().eq("phone", phone));
	}

	@Override
	public Long saveUser(AppRegisterDTO appRegisterDTO) {
		UserEntity user = new UserEntity();
		BeanUtils.copyProperties(appRegisterDTO, user);
		//校验数据
		ValidatorUtils.validateEntity(appRegisterDTO);

		/**
		 * 初始化用户注册信息
		 **/
		//会员等级为普通会员
		user.setMemberLevelId((long)4);
		//性别：0->未知；1->男；2->女
		if (appRegisterDTO.getGender() != 1 && appRegisterDTO.getGender() != 2) { user.setGender(0); }
		//帐号启用状态:0->禁用；1->启用
		user.setStatus(1);
		//用户来源：0->管理员添加；1->app注册；2->网页注册
		user.setSourceType(1);
		//初始积分为0
		user.setIntegration(0);
		//初始成长值为0
		user.setGrowth(0);
		//剩余抽奖次数为0
		user.setLuckeyCount(0);

		//对密码进行sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);

		//保存用户
		this.save(user);
		return user.getId();
	}
}
